const std = @import("std");
const load_json_from_file = @import("root.zig").load_json_from_file;

const fixed_dirty_json = @import("root.zig").fixed_dirty_json;

const compile = @import("pcre.zig").compile;
const find = @import("pcre.zig").find;

const replace = @import("pcre.zig").replace_all;
pub fn main() !void {
    // try test_load_file_json();
    try pcre_example();
}

fn test_load_file_json() !void {
    const path = "dirty_json";

    try load_json_from_file(path);
}

fn test_fixed_json_str() !void {
    const json_str =
        \\{
        \\  "name": "Alice",
        \\  "age": 30,
        \\  "is_student": false,
        \\  "scores": [95, 89, 78]
        \\}
    ;

    try fixed_dirty_json(json_str);
}

pub fn pcre_example() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    var file = try std.fs.cwd().openFile("dirty_json", .{});

    defer _ = gpa.deinit();
    const allocator = gpa.allocator();
    // var buffer: [std.fs.max_path_bytes]u8 = undefined;

    const file_size = try file.getEndPos();
    if (file_size > std.math.maxInt(usize)) {
        return error.FileTooLarge;
    }
    const buffer = try allocator.alloc(u8, file_size);

    defer file.close();

    const bytes = try file.readAll(buffer);

    defer allocator.free(buffer);
    std.debug.assert(bytes == file_size);
    const result = try allocator.dupe(u8, buffer);

    defer allocator.free(result);

    const cleaned_result = try remove_comment(allocator, result);
    std.debug.print("result: {s}\n", .{cleaned_result});
    defer allocator.free(cleaned_result);
}

pub fn remove_comment(allocator: std.mem.Allocator, subject: []const u8) ![]const u8 {
    const comment = "//.*";
    const result = try replace(allocator, comment, subject, "");

    return @constCast(result);
}
